#include "DocumentPreview.h"

#include "simodo/shell/access/LspAccess_interface.h"
#include "simodo/shell/document/ViewAdaptor_interface.h"
#include "simodo/shell/document/DocumentAdaptor_interface.h"

#include <QFileInfo>
#include <QComboBox>
#include <QJsonObject>

#include <fstream>
#include <chrono>

DocumentPreview::DocumentPreview(shell::Runner_plugin * plugin, shell::Access_interface & shell)
    : _plugin(plugin)
    , _shell(shell)
{
    _run_management = _shell.getRunnerManagement();

    connect(this, &DocumentPreview::notification_received_signal, this, &DocumentPreview::notification_received_slot);
    connect(this, &DocumentPreview::ran_signal, this, &DocumentPreview::ran_slot);
    connect(this, &DocumentPreview::paused_signal, this, &DocumentPreview::paused_slot);
    connect(this, &DocumentPreview::stoped_signal, this, &DocumentPreview::stoped_slot);
}

QString DocumentPreview::name() const
{
    return tr("Document Preview");
}

QString DocumentPreview::description() const
{
    return tr("Document preview");
}

bool DocumentPreview::isRunnable(const QString & path) 
{
    return QFileInfo(path).suffix() == "md";
}

bool DocumentPreview::startModeling(const QString & path) 
{
    _error_text = "";

    const shell::ViewAdaptor_interface * va = _shell.getCurrentViewAdaptor();

    if (va == nullptr)
        return false;

    const std::shared_ptr<shell::DocumentAdaptor_interface> da = va->document_adaptor();

    if (!da)
        return false;

    auto [line,col] = va->getLineCol();
    
    QJsonObject data;
    data.insert("file", QFileInfo(path).fileName());
    data.insert("text", da->text());
    data.insert("line", line);
    data.insert("column", col);

    bool ok = _shell.sendDataToPanel("markdown-preview", "", data);

    _shell.setPanelTitle("markdown-preview", QFileInfo(path).fileName());

    return ok;
}

bool DocumentPreview::pauseModeling() 
{
    return false;
}

bool DocumentPreview::stopModeling() 
{
    return false;
}

QWidget *DocumentPreview::getToolbarWidget()
{
    return nullptr;
}

void DocumentPreview::notification_received_slot(const QString text)
{
    if (_run_management)
        _run_management->received(text);
}

void DocumentPreview::ran_slot()
{
    if (_run_management)
        _run_management->started();
}

void DocumentPreview::paused_slot()
{
    if (_run_management)
        _run_management->paused();
}

void DocumentPreview::stoped_slot()
{
    if (_run_management)
        _run_management->stoped();
}

